<?php
/**
 * DMFramework
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @url http://dmframework.nl
 */

/**
 * This class can be used to load configuration file(s) where content is saved
 * used .ini style formatting, you can use true and false because it will convert
 * those two values in "real" true and false.
 * 
 * @license Copyright 2012 Dillen Meijboom under the Apache license version 2.0 (http://apache.org/licenses/LICENSE-2.0)
 * @author Dillen Meijboom <info@dillenm.nl>
 * @package System.Core.Config
 */
class Dmf_Config_Ini
{
    /**
     * All configuration settings
     * 
     * @var array 
     */
    private $_config = array();
    
    /**
     * Constructor
     * 
     * @param string $filename
     * @throws Dmf_Exception_FileNotFound 
     */
    public function __construct( $filename )
    {
        if ( ! file_exists( $filename ) )
        {
            throw new Dmf_Exception_FileNotFound( 'Config file: "' . $filename . '" not found.' );
        }
        
        $this->_config = parse_ini_file( $filename, true );
        
        $this->_fixValues( $this->_config );
    }
    
    /**
     * True and false in .ini are converted to zero and one
     * but since we really need booleans we convert them back.
     * 
     * @param array $array 
     */
    private function _fixValues( &$array )
    {
        foreach( $array as $key => &$value )
        {
            if ( is_array( $value ) )
            {
                $this->_fixValues( $value );
                continue;
            }
            
            $value = ( $value == 1 ? true : $value );
            $value = ( $value == '' && strlen( $value ) == 0 ? false : $value );
            
            if ( $key == 'path' && $value == 'default' )
            {
                $value = dirname( dirname( dirname( dirname( __FILE__ ) ) ) );
            }
        }
    }
    
    /**
     * Return all settings as an object
     * 
     * @param array $array
     * @return Dmf_Stdclass 
     */
    public function asObject( $array = null )
    {
        $std = new Dmf_Stdclass;
        $array = ( $array === null ) ? $this->_config : $array;

        foreach( $array as $index => $value )
        {
            if ( is_array( $value ) )
            {
                $std->$index = $this->asObject( $value );

                continue;
            }

            $std->$index = $value;
        }

        return (object)$std;
    }
    
    /**
     * Return all configuration settings as an array
     * 
     * @return array
     */
    public function asArray()
    {
        return (array)$this->_config;
    }
}